import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home',
    children: [
      { path: 'home', component: () => import('@/views/home') },
      { path: 'user-info', component: () => import('@/views/user/userInfo.vue') },
      { path: 'user-avatar', component: () => import('@/views/user/userAvatar.vue') },
      { path: 'user-pwd', component: () => import('@/views/user/userPwd.vue') },
      { path: 'art-cate', component: () => import('@/views/article/artCate.vue') },
      { path: 'art-list', component: () => import('@/views/article/artList.vue') },
      { path: 'comment-art', component: () => import('@/views/comment/articlecomment.vue') },
      { path: 'comment-people', component: () => import('@/views/comment/peoplecomment.vue') },
      { path: 'extend-card', component: () => import('@/views/extend/card.vue') },
      { path: 'extend-link', component: () => import('@/views/extend/link.vue') },
      { path: 'extend-like', component: () => import('@/views/extend/like.vue') },
      { path: 'user-right', component: () => import('@/views/right/user.vue') },
      { path: 'menu-right', component: () => import('@/views/right/menu.vue') }
    ]
    // redirect: '/login'
  },
  {
    path: '/reg',
    component: () => import('@/views/register')
    // 懒加载，路由转换到/reg 才能去加载对应组件，
    // 好处：首页加载速度更快
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  }
]

const router = new VueRouter({
  routes
})

// 路由白名单, 不需要token验证
const whiteList = ['/login', '/reg']

router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    if (token && !store.state.userInfo.user_name) {
      store.dispatch('getUserInfoActions')
    }
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router
